/*
 * @Author: yuqy
 * @Date: 2023-04-11 13:49:33
 * @LastEditors: yuqy
 * @LastEditTime: 2023-10-21 15:11:33
 * @Descripttion: -
 */
import { postLogin, getUserInfo, deleteLoginLogout } from '@/api/user'
import route from '@/router'
import { Notice } from "view-ui-plus";
import util from '@/libs/util'
export default {
  namespaced: true,
  state: {
    userInfo: {},
    token: '',
    demo: ''
  },
  getters: {
    getUserInfo: (state) => {
      return state.userInfo
    },
    getUserPhone: (state) => {
      return state.userInfo.phone || '我是手机号'
    },
    getUserUid: (state) => {
      return state.userInfo.phone ? state.userInfo.phone.substring(7, 11) : null
    },
    
    getUserNickName: (state) => {
      return state.userInfo.name || '我是小丁猫';
    }
  },
  actions: {
    // 异步过程，调用mutations中方法改变state
    // asyncUpdateUserInfo(store, newData) { // 第一个参数是vuex固定的参数，不需要手动去传递
        // store.commit("updateUserInfo", newData)
    // },
    /**
     * @name: 退出登录
     * @msg: 
     * @param {*} commit
     * @param {*} params
     * @return {*}
     */    
    loginOut ({ commit }) {
      return new Promise(async (resolve, reject) => {
        route.push('login');
        await deleteLoginLogout(); 
        commit({ type: 'updateToken', token: ''});
        return resolve(true);
      })
    },
    postLogin ({ commit }, params) {
      return new Promise((resolve, reject) => {
        postLogin(params).then(data => {
          const token = data.token
          if (!token) return resolve(false);
          commit({
            type: 'updateToken',
            token
          })
          resolve(data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    getUserInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getUserInfo().then(data => {
          if (!data) {
            return resolve({})
          }
          if (data.inspectStatus == 1) {
            Notice.error({ title: '提示', desc: '您的账号还未开通双师功能，请联系管理员' })
            return resolve(data)
          }
          commit({
            type: 'updateUserInfo',
            userInfo: data
          })
          resolve(data)
        }).catch(err => {
          reject(err)
        })
      })
    },
  },
  mutations: {
    updateUserInfo(state, { userInfo }) {
      state.userInfo = userInfo
    },
    updateToken (state, { token }) {
      state.token = token
      util.setToken(token)
    }
  }
}